#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试HTTP请求与Flask测试客户端差异
"""

import requests
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from backend.app import create_app
from flask import g

def debug_http_vs_flask():
    """调试HTTP请求与Flask测试客户端的差异"""
    print("=== HTTP请求与Flask测试客户端差异调试 ===")
    
    app = create_app()
    test_url = '/api/netdisk/download/43/bb/43bb0dd030fe6beb70e92fdce9b1e560.mp4'
    
    # 1. Flask测试客户端测试
    print("\n=== Flask测试客户端 ===")
    with app.test_client() as client:
        response = client.get(test_url)
        print(f"状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")
        if response.content_type.startswith('application/json'):
            print(f"JSON响应: {response.get_json()}")
        else:
            print(f"响应大小: {len(response.data)} bytes")
    
    # 2. 直接HTTP请求测试
    print("\n=== 直接HTTP请求 ===")
    try:
        response = requests.get(f"http://127.0.0.1:5000{test_url}", timeout=10)
        print(f"状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")
        if response.headers.get('content-type', '').startswith('application/json'):
            print(f"JSON响应: {response.json()}")
        else:
            print(f"响应大小: {len(response.content)} bytes")
    except Exception as e:
        print(f"HTTP请求失败: {e}")
    
    # 3. 检查路由匹配
    print("\n=== 路由匹配检查 ===")
    with app.test_request_context(test_url):
        from flask import request
        print(f"请求URL: {request.url}")
        print(f"请求路径: {request.path}")
        print(f"匹配的端点: {request.endpoint}")
        
        # 获取视图函数
        if request.endpoint:
            view_func = app.view_functions.get(request.endpoint)
            if view_func:
                print(f"视图函数: {view_func.__name__}")
                print(f"视图函数模块: {view_func.__module__}")
                print(f"是否有装饰器: {hasattr(view_func, '__wrapped__')}")
                
                # 检查装饰器链
                func = view_func
                level = 0
                while hasattr(func, '__wrapped__'):
                    level += 1
                    print(f"装饰器层级 {level}: {func.__name__}")
                    func = func.__wrapped__
                print(f"最终函数: {func.__name__}")
    
    # 4. 手动调用装饰器测试
    print("\n=== 手动装饰器测试 ===")
    from api.netdisk import download_file_by_path
    from utils.auth import login_required
    
    # 创建一个测试函数
    @login_required
    def test_decorated_function():
        return "success"
    
    with app.test_request_context(test_url, headers={}):
        try:
            result = test_decorated_function()
            print(f"装饰器测试结果: {result}")
            print(f"结果类型: {type(result)}")
            if hasattr(result, 'status_code'):
                print(f"状态码: {result.status_code}")
        except Exception as e:
            print(f"装饰器测试异常: {e}")
    
    # 5. 检查应用配置
    print("\n=== 应用配置检查 ===")
    print(f"调试模式: {app.debug}")
    print(f"测试模式: {app.testing}")
    print(f"配置类: {app.config.get('ENV')}")
    
    # 6. 检查蓝图注册
    print("\n=== 蓝图注册检查 ===")
    for blueprint_name, blueprint in app.blueprints.items():
        print(f"蓝图: {blueprint_name} -> {blueprint}")
        if blueprint_name == 'netdisk':
            print(f"  URL前缀: {blueprint.url_prefix}")
            print(f"  静态文件夹: {blueprint.static_folder}")

if __name__ == '__main__':
    debug_http_vs_flask()